﻿function attachEvent(object, event, handler)
{
	if (object.addEventListener)
	{
		object.addEventListener(event.substr(2), handler, false);
	}
	else if (object.attachEvent)
	{
		object.attachEvent(event, handler);
	}
}

var PhotoOfTheDay =
{
	Load: function()
	{
		document.getElementById("photo").style.display = "none";

		var img = document.getElementById("photooftheday");
		if (img && img.parentNode)
		{
			img.parentNode.removeChild(img);
		}

		var params = {};
		params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
		params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;

		gadgets.io.makeRequest("http://photography.nationalgeographic.com/photography/photo-of-the-day/", PhotoOfTheDay.Display, params);
	},

	Display: function(Response)
	{
		if (Response && Response.text)
		{
			var ImageSource = null;
			var text = Response.text.replace(new RegExp("\n", "g"), "").replace(new RegExp("\r", "g"), "");
			var re = new RegExp("<div class=\"primary_photo\">(.+?)<\/div>");
			var match = re.exec(text);

			if (match && match.length > 1)
			{
				text = match[1];

				re = new RegExp("src=\"(.+?)\"");
				match = re.exec(text);

				if (match && match.length > 1)
				{
					ImageSource = match[1];
				}
			}

			if (ImageSource)
			{
				var container = document.getElementById("photo");
				container.style.display = "block";

				var img = document.createElement("img");
				img.id = "photooftheday";
				img.alt = "";
				img.src = ImageSource;
				PhotoOfTheDay.Resize(null, img);

				document.getElementById("nationalgeographic").appendChild(img);

				attachEvent(img, "onload", gadgets.window.adjustHeight);
				attachEvent(window, "onresize", PhotoOfTheDay.Resize);
			}

		}
	},

	Resize: function(e, Image)
	{
		var container = document.getElementById("photo");
		var img = Image || document.getElementById("photooftheday");

		if (container && img)
		{
			img.style.width = container.clientWidth + "px";
			img.style.height = "auto";
		}

		gadgets.window.adjustHeight();
	}
};


var Analytics =
{
	Initialized: false,

	Init: function()
	{
		if (!Analytics.Initialized)
		{
			_gaq = window._gaq || [];
			_gaq.push(["_setAccount", "UA-18423784-3"]);
			_gaq.push(["_trackPageview"]);

			var script = document.createElement("script");
			script.type = "text/javascript";
			script.async = true;
			script.src = (document.location.protocol == "https:" ? "https://ssl" : "http://www") + ".google-analytics.com/ga.js";

			var head = document.getElementsByTagName("head")[0] || document.getElementsByTagName("body")[0];

			if (head)
			{
				head.insertBefore(script, head.firstChild);
			}

			Analytics.Initialized = true;
		}
	}
};